<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/09/07
 * Time: 13:29
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\wms;

use app\admin\controller\BaseController;
use app\common\model\ProductBrand;
use app\common\service\product\ProductService;
use think\facade\Validate;

class BrandController extends BaseController
{
    /**
     * 品牌首页
     * @return string
     * @date 2020/11/25
     * @throws \think\exception\DbException
     * @author longli
     */
    public function index()
    {
        if($this->request->isAjax())
        {
            $brand = ProductBrand::order("sort desc, brand_id desc");
            $where = [];
            $name = $this->request->request("name");
            if(!empty($name))
            {
                $brand->whereRaw("name_ch like :a or name_en like :b", ["a"=>"%$name%", "b"=>"%$name%"]);
            }
            $limit = $this->getPageSize();
            $brand = $brand->paginate($limit);
            $this->assign("list", $brand->getCollection());
            $this->assign("page", $brand->render());
            return $this->fetch("lists");
        }
        return $this->fetch("index");
    }

    /**
     * 添加品牌
     * @date 2020/09/14
     * @author longli
     */
    public function add()
    {
        $brandId = $this->request->request("brand_id");
        if(!empty($brandId)) $this->assign("brand", ProductBrand::get($brandId));
        return $this->fetch("add");
    }

    /**
     * 更新品牌信息
     * @date 2020/09/14
     * @author longli
     */
    public function save()
    {
        if($this->request->isPost())
        {
            $validate = Validate::make([
                'name_ch'  => 'require',
            ],[
                'name_ch.require' => '品牌中文名必填',
            ]);
            $data = $this->request->post();
            if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));
            if(!isset($data['status'])) $data['status'] = ProductBrand::IS_NO;
            if(!isset($data['is_auth'])) $data['is_auth'] = ProductBrand::IS_NO;
        }
        else
        {
            $validate = Validate::make([
                'brand_id'  => 'require',
            ],[
                'brand_id.require' => '非法请求',
            ]);
            $data = $this->request->only(['brand_id', 'status'], 'get');
            if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));
        }
        ProductService::getInstance()->addBrand($data)
            ? $this->success('操作成功')
            : $this->error('操作失败');
    }

    /**
     * 删除品牌
     * @date 2020/09/14
     * @author longli
     */
    public function delete()
    {
        $brandId = $this->request->request("ids");
        if(empty($brandId)) $this->error('参数错误');
        ProductBrand::destroy($brandId);
        $this->success('删除成功');
    }
}